<template>
  <div class="create-attraction">
    <div class="page-header">
      <div class="title-section">
        <h1>添加景点</h1>
        <p class="subtitle">创建新的景点信息，丰富网站内容</p>
      </div>
      <el-button @click="goBack" :icon="ArrowLeft">返回列表</el-button>
    </div>
    
    <el-card class="form-card">
      <el-form
        ref="attractionFormRef"
        :model="attractionForm"
        :rules="attractionRules"
        label-width="100px"
        label-position="top"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="景点名称" prop="name">
                  <el-input v-model="attractionForm.name" placeholder="请输入景点名称" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="所属类别" prop="categoryId">
                  <el-select v-model="attractionForm.categoryId" placeholder="请选择类别" style="width: 100%">
                    <el-option
                      v-for="item in categories"
                      :key="item.categoryId"
                      :label="item.categoryName"
                      :value="item.categoryId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="景点地址" prop="address">
              <el-input v-model="attractionForm.address" placeholder="请输入景点详细地址" />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number 
                    v-model="attractionForm.longitude" 
                    :precision="6" 
                    :step="0.000001" 
                    style="width: 100%"
                    placeholder="例如: 120.1438"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number 
                    v-model="attractionForm.latitude" 
                    :precision="6" 
                    :step="0.000001" 
                    style="width: 100%"
                    placeholder="例如: 30.2360"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="景点简介" prop="description">
              <el-input
                v-model="attractionForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入景点简介，简要描述景点特色"
              />
            </el-form-item>
            
            <el-form-item label="标签" prop="tags">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                + 添加标签
              </el-button>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="详细信息" name="detail">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="门票价格" prop="ticketPrice">
                  <el-input v-model="attractionForm.ticketPrice" placeholder="例如：230元起，免费等" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="开放时间" prop="openingHours">
                  <el-input v-model="attractionForm.openingHours" placeholder="例如：09:00-17:00，全天开放等" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="attractionForm.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="网站" prop="website">
                  <el-input v-model="attractionForm.website" placeholder="请输入景点官网地址" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="详细介绍" prop="content">
              <el-input
                v-model="attractionForm.content"
                type="textarea"
                :rows="6"
                placeholder="请输入景点的详细介绍，可包含历史背景、特色等"
              />
            </el-form-item>
            
            <el-form-item label="交通指南" prop="transportation">
              <el-input
                v-model="attractionForm.transportation"
                type="textarea"
                :rows="3"
                placeholder="请输入到达景点的交通方式，如公交路线、自驾路线等"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="图片管理" name="images">
            <el-form-item label="封面图片" prop="coverImage">
              <div class="cover-uploader-container">
                <el-upload
                  class="cover-uploader"
                  :action="uploadCoverAction"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeUpload"
                  name="files"
                >
                  <img v-if="attractionForm.coverImage" :src="attractionForm.coverImage" class="cover-preview" />
                  <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip upload-tip-with-margin">
                  <p>请上传景点封面图片，建议尺寸 1200x800 像素</p>
                  <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </el-form-item>
            
            <el-form-item label="景点图片集">
              <div v-if="attractionForm.images && attractionForm.images.length > 0" class="existing-images">
                <div v-for="(image, index) in attractionForm.images" :key="index" class="image-item">
                  <img :src="image" class="preview-image" @click="previewImage(image)" />
                  <div class="image-actions">
                    <el-button
                      type="danger"
                      size="small"
                      circle
                      @click="removeImage(index)"
                      :icon="Delete"
                    ></el-button>
                  </div>
                </div>
              </div>
              
              <el-upload
                :action="uploadGalleryAction"
                :headers="uploadHeaders"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                multiple
                :limit="10"
                accept="image/*"
                list-type="picture-card"
                name="files"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="发布设置" name="settings">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="attractionForm.status">
                    <el-radio :label="1">上线</el-radio>
                    <el-radio :label="0">下线</el-radio>
                  </el-radio-group>
                  <div class="form-tip">
                    <p>上线：景点信息将在前台展示</p>
                    <p>下线：景点信息将暂时隐藏，不在前台展示</p>
                  </div>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="评分" prop="rating">
                  <div class="rating-container">
                    <el-slider
                      v-model="attractionForm.rating"
                      :min="0"
                      :max="5"
                      :step="0.1"
                      :format-tooltip="formatRatingTooltip"
                      show-stops
                      show-input
                      :show-input-controls="false"
                      input-size="small"
                      style="width: 80%;"
                    />
                    <div class="rating-value">{{ attractionForm.rating.toFixed(1) }}</div>
                  </div>
                  <div class="rating-stars">
                    <el-rate
                      v-model="attractionForm.rating"
                      :max="5"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :texts="['1分', '2分', '3分', '4分', '5分']"
                      :allow-half="true"
                      show-text
                      @change="handleRateChange"
                    />
                  </div>
                  <div class="form-tip">
                    <p>设置景点评分，将影响景点在前台的排序和展示</p>
                    <p>支持0.1分的精度，范围0-5分</p>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        
        <div class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus, ArrowLeft, Picture, Delete } from '@element-plus/icons-vue';
import { getAllCategories } from '@/api/category';
import { addAttraction } from '@/api/attraction';

const router = useRouter();
const submitting = ref(false);
const activeTab = ref('basic');
const InputRef = ref(null);

// 表单
const attractionFormRef = ref(null);
const attractionForm = reactive({
  name: '',
  categoryId: '',
  address: '',
  longitude: null,
  latitude: null,
  description: '',
  ticketPrice: '',
  openingHours: '',
  contactPhone: '',
  website: '',
  content: '',
  transportation: '',
  coverImage: '',
  images: [],
  status: 1,
  tags: [],
  rating: 0
});

// 标签相关
const inputVisible = ref(false);
const inputValue = ref('');
const dynamicTags = ref([]);

// 类别列表
const categories = ref([]);

// 图片上传
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const uploadCoverAction = `${import.meta.env.VITE_API_BASE_URL}/attraction/upload/cover`;
const uploadGalleryAction = `${import.meta.env.VITE_API_BASE_URL}/attraction/upload/gallery`;
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  };
});

// 表单验证规则
const attractionRules = {
  name: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { max: 50, message: '景点名称长度不能超过50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属类别', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入景点地址', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入景点简介', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请上传景点封面图片', trigger: 'change' }
  ]
};

// 获取类别列表
const fetchCategories = async () => {
  try {
    const response = await getAllCategories();
    if (response.code === 200) {
      categories.value = response.data;
    } else {
      ElMessage.error(response.message || '获取类别列表失败');
    }
  } catch (error) {
    console.error('获取类别列表失败:', error);
    ElMessage.error('获取类别列表失败，请稍后再试');
    
    // 开发环境下使用模拟数据
    if (import.meta.env.DEV) {
      categories.value = [
        { categoryId: 1, categoryName: '自然风光' },
        { categoryId: 2, categoryName: '历史古迹' },
        { categoryId: 3, categoryName: '主题公园' },
        { categoryId: 4, categoryName: '城市地标' },
        { categoryId: 5, categoryName: '乡村风情' }
      ];
    }
  }
};

// 标签相关方法
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
  attractionForm.tags = dynamicTags.value;
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (!dynamicTags.value.includes(inputValue.value)) {
      dynamicTags.value.push(inputValue.value);
      attractionForm.tags = dynamicTags.value;
    }
  }
  inputVisible.value = false;
  inputValue.value = '';
};

// 封面图片上传成功
const handleCoverSuccess = (response) => {
  if (response.code === 200 && response.data && response.data.length > 0) {
    attractionForm.coverImage = response.data[0]; // 使用返回的第一个URL
    ElMessage.success('封面图片上传成功');
  } else {
    ElMessage.error(response.message || '封面图片上传失败');
  }
};

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 移除图片
const handleRemove = (file) => {
  // 检查file是否有url属性（Element Plus上传组件的文件对象）
  if (file.url) {
    const index = attractionForm.images.indexOf(file.url);
    if (index !== -1) {
      attractionForm.images.splice(index, 1);
    }
  } 
  // 如果file是原始URL字符串（我们自己添加的图片）
  else if (typeof file === 'string') {
    const index = attractionForm.images.indexOf(file);
    if (index !== -1) {
      attractionForm.images.splice(index, 1);
    }
  }
  // 如果file有response属性（刚上传的文件）
  else if (file.response && file.response.data && file.response.data.length > 0) {
    const url = file.response.data[0];
    const index = attractionForm.images.indexOf(url);
    if (index !== -1) {
      attractionForm.images.splice(index, 1);
    }
  }
};

// 直接从图片集中移除图片（用于已存在的图片）
const removeImage = (index) => {
  attractionForm.images.splice(index, 1);
};

// 预览图片
const previewImage = (url) => {
  dialogImageUrl.value = url;
  dialogVisible.value = true;
};

// 图片集上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 200 && response.data) {
    // 检查返回的数据格式，适配API返回结构
    if (Array.isArray(response.data)) {
      // 如果返回的是数组，将所有URL添加到图片集
      response.data.forEach(url => {
        attractionForm.images.push(url);
      });
    } else if (typeof response.data === 'string') {
      // 如果返回的是单个URL字符串
      attractionForm.images.push(response.data);
    } else if (response.data.urls && Array.isArray(response.data.urls)) {
      // 如果返回的是包含urls数组的对象
      response.data.urls.forEach(url => {
        attractionForm.images.push(url);
      });
    }
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.message || '图片上传失败');
  }
};

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 格式化评分提示
const formatRatingTooltip = (val) => {
  return val.toFixed(1) + '分';
};

// 处理评分变化
const handleRateChange = (value) => {
  // 确保评分值保留一位小数
  attractionForm.rating = parseFloat(value.toFixed(1));
};

// 提交表单
const submitForm = () => {
  attractionFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 准备提交的数据，根据后端AttractionDTO的结构进行调整
        const submitData = {
          categoryId: attractionForm.categoryId,
          name: attractionForm.name,
          description: attractionForm.description,
          detail: attractionForm.content,
          trafficGuide: attractionForm.transportation,
          longitude: attractionForm.longitude,
          latitude: attractionForm.latitude,
          address: attractionForm.address,
          coverImages: attractionForm.coverImage ? [attractionForm.coverImage] : [],
          imageGallery: attractionForm.images,
          openingHours: attractionForm.openingHours,
          ticketPrice: attractionForm.ticketPrice,
          contactPhone: attractionForm.contactPhone,
          website: attractionForm.website,
          tags: dynamicTags.value,
          status: attractionForm.status || 1, // 默认状态为1(正常)
          avgRating: attractionForm.rating,
        };
        
        const response = await addAttraction(submitData);
        if (response.code === 200) {
          ElMessage.success('添加景点成功');
          router.push('/admin/attractions');
        } else {
          ElMessage.error(response.message || '添加景点失败');
        }
      } catch (error) {
        console.error('添加景点失败:', error);
        ElMessage.error('添加景点失败，请稍后再试');
      } finally {
        submitting.value = false;
      }
    } else {
      // 表单验证失败，切换到相应的标签页
      if (attractionFormRef.value.fields.some(field => 
        field.prop.startsWith('name') || 
        field.prop.startsWith('categoryId') || 
        field.prop.startsWith('address') || 
        field.prop.startsWith('description'))) {
        activeTab.value = 'basic';
      } else if (attractionFormRef.value.fields.some(field => 
        field.prop.startsWith('coverImage') || 
        field.prop.startsWith('images'))) {
        activeTab.value = 'images';
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  attractionFormRef.value.resetFields();
  attractionForm.images = [];
  attractionForm.coverImage = '';
  dynamicTags.value = [];
  activeTab.value = 'basic';
};

// 返回列表
const goBack = () => {
  router.push('/admin/attractions');
};

onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.create-attraction {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h1 {
  margin: 0 0 5px;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.cover-uploader-container {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.cover-uploader {
  width: 300px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 28px;
  height: 28px;
}

.cover-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.upload-tip-with-margin {
  margin-left: 30px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.mx-1 {
  margin-left: 4px;
  margin-right: 4px;
}

.ml-1 {
  margin-left: 4px;
}

.w-20 {
  width: 80px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .cover-uploader-container {
    flex-direction: column;
  }
  
  .cover-uploader {
    width: 100%;
  }
}

.existing-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 20px; /* 添加底部间距，与上传按钮分开 */
}

.image-item {
  position: relative;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 10;
}

.rating-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.rating-stars {
  margin-bottom: 10px;
}

.rating-value {
  font-size: 18px;
  font-weight: bold;
  color: #FF9900;
  min-width: 40px;
  text-align: center;
}
</style>